<?php

namespace app\api\controller;

use app\api\lib\SuPengJun;
use app\common\model\NoticeModel;
use app\common\model\user\UserModel;
use think\Request;

class Notice extends Controller
{
    protected array $middleware = [
        'api' => ['except' => ['bar_badge']],
        'orCheck' => ['only' => ['bar_badge']]
    ];

    /**
     * 导航栏消息数量
     */
    public function bar_badge(Request $request)
    {
        $uid = $request->uid;
        $data = NoticeModel::where('user_id', $uid)->where('read', 0)->count();
        return success('success', $data);
    }

    /**
     * 通知列表
     * @param array $type 类型:1=,2=,3=
     * @return json|array
     * @throws \AlibabaCloud|Client|Result|array
     */
    public function list(Request $request)
    {
        $uid = $request->uid;
        $type = $request->get('type', 0);
        $condition[] = ['user_id', '=', $uid];
        if ($type) $condition[] = ['type', '=', $type];
        $data = NoticeModel::where($condition)
            ->order('read', 'asc')
            ->order('id', 'desc')
            ->field('id,launch_id,title,content,avatar_url,content_url,read,type,create_time')
            ->paginate(12);
        $data->map(function ($v) {
            $v['create_time_str'] = SuPengJun::timeStr($v['create_time']);
            if ($v['launch_id'] > 1) $v['user'] = UserModel::where('id', $v['launch_id'])->field('name,avatar')->find();
            return $v;
        });
        return success('success', $data);
    }

    /**
     * 消息通知-消息数量
     */
    public function read_count(Request $request)
    {
        $uid = $request->uid;
        $condition[] = ['user_id', '=', $uid];
        $condition[] = ['read', '=', 0];
        $data[0] = NoticeModel::where($condition)->where('type', 1)->count();
        $data[1] = NoticeModel::where($condition)->where('type', 2)->count();
        $data[2] = NoticeModel::where($condition)->where('type', 3)->count();
        return success('success', $data);
    }

    /**
     * 通知-设置已读（$id=0时，设置全部已读）
     * @param array $id 通知ID
     * @return json|array
     * @throws \AlibabaCloud|Client|Result|array
     */
    public function read(Request $request)
    {
        $uid = $request->uid;
        $id = $request->post('id', 0);
        $condition[] = ['user_id', '=', $uid];
        if ($id) $condition[] = ['id', '=', $id];
        NoticeModel::where($condition)->update(['read' => 1]);
        return success('操作完成 🎉');
    }

    /**
     * 删除通知
     * @param array $param 参数类型参数名参数作用
     * @return json|array
     * @throws \AlibabaCloud|Client|Result|array
     */
    public function del(Request $request)
    {
        $uid = $request->uid;
        $id = $request->post('id', 0);
        $condition[] = ['user_id', '=', $uid];
        $condition[] = ['id', '=', $id];
        NoticeModel::where($condition)->delete();
        return success('删除成功！');
    }
}
